"""
自定义中间件
"""


class ContentSecurityPolicyMiddleware:
    """
    添加 Content Security Policy 头部，允许必要的脚本执行
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # 设置宽松的 CSP 策略以允许 marked.js 和其他必要的库工作
        # 在生产环境中应该更加严格
        csp_policy = (
            "default-src 'self'; "
            "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; "
            "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
            "img-src 'self' data: https:; "
            "font-src 'self' data: https://cdn.jsdelivr.net; "
            "connect-src 'self'; "
            "frame-ancestors 'none';"
        )
        
        response['Content-Security-Policy'] = csp_policy
        return response
